package com.ewanghuiju.app.ui.pintuan.activity;

import android.annotation.SuppressLint;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.animation.Animation;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ewanghuiju.app.R;
import com.ewanghuiju.app.app.Constants;
import com.ewanghuiju.app.base.BaseActivity;
import com.ewanghuiju.app.base.contract.pintuan.PintuanDetailsContract;
import com.ewanghuiju.app.component.RxBus;
import com.ewanghuiju.app.model.bean.response.PintuanHeadListResponBean;
import com.ewanghuiju.app.model.bean.response.PintuanShopListResponBean;
import com.ewanghuiju.app.model.bean.response.RuleBean;
import com.ewanghuiju.app.model.bean.response.ShareResponBean;
import com.ewanghuiju.app.model.event.SendEvent;
import com.ewanghuiju.app.presenter.pintuan.PintuanDetailsPresenter;
import com.ewanghuiju.app.ui.pintuan.adapter.PintuanTjtgAdapter;
import com.ewanghuiju.app.ui.pintuan.adapter.PintuanheadListAdapter;
import com.ewanghuiju.app.util.ClipboardUtils;
import com.ewanghuiju.app.util.LoadingDialogUtils;
import com.ewanghuiju.app.util.PermissionUtil;
import com.ewanghuiju.app.util.StartActivityUtil;
import com.ewanghuiju.app.util.StringUtil;
import com.ewanghuiju.app.util.ToastUtil;
import com.ewanghuiju.app.util.nodoubleclick.AntiShake;
import com.ewanghuiju.app.util.thread.LoadImageDataThread;
import com.ewanghuiju.app.widget.popupwindow.PintuanFuwuPopup;
import com.ewanghuiju.app.widget.popupwindow.ShareShopPopup;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureMediaScannerConnection;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.luck.picture.lib.tools.ToastUtils;
import com.muddzdev.styleabletoast.StyleableToast;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author sj  qq:751943509
 * @class 拼团详情页面   参团人信息
 * * @time 2020/2/19
 */
public class PintuanDetailsActivity extends BaseActivity<PintuanDetailsPresenter> implements PintuanDetailsContract.View {
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    //拼团状态
    @BindView(R.id.tv_pintuan_status)
    TextView tvPintuanStatus;
    //拼团号加倒计时
    @BindView(R.id.tv_pintuan_no)
    TextView tvPintuanNo;
    //拼团用户信息列表
    @BindView(R.id.pintuan_users_recycleview)
    RecyclerView pintuanUsersRecycleview;
    @BindView(R.id.tv_share_join)
    TextView tvShareJoin;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_shop_title)
    TextView tvShopTitle;
    //服务弹框
    private PintuanFuwuPopup pintuanFuwuPopup;
    private PintuanheadListAdapter pintuanheadListAdapter;


    private String groupId;

    private CountDownTimer countDownTimer;

    private PintuanHeadListResponBean mPintuanHeadListResponBean;

    private ShareShopPopup shareShopPopup;

    private PintuanTjtgAdapter pintuanTjtgAdapter;

    @Override
    protected int getLayout() {
        return R.layout.activity_pintuan_details;
    }

    @Override
    protected void initEventAndData() {
        groupId = getIntent().getStringExtra(Constants.PINTUAN_GROUP_ID);
        if (TextUtils.isEmpty(groupId)) {
            StyleableToast.makeText(mContext, "未获取到信息", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        LoadingDialogUtils.show(mContext);
        mPresenter.getPtigroupUserImage(groupId + "");
    }

    @Override
    protected void intSmartRefreshLayout() {
//        super.intSmartRefreshLayout();
        if (refreshLayout != null) {
            refreshLayout.setEnableRefresh(true);
            refreshLayout.setEnableLoadMore(false);
            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                    if (TextUtils.isEmpty(groupId)) {
                        StyleableToast.makeText(mContext, "未获取到信息", Toast.LENGTH_SHORT, R.style.mytoast).show();
                        return;
                    }
                    LoadingDialogUtils.show(mContext);
                    mPresenter.getPtigroupUserImage(groupId + "");
                }
            });
        }

    }

    private void initHotList(List<PintuanShopListResponBean> pintuanShopListResponBeanList) {
        if (pintuanTjtgAdapter != null) {
            pintuanTjtgAdapter.setNewData(pintuanShopListResponBeanList);
            return;
        }
        pintuanTjtgAdapter = new PintuanTjtgAdapter(R.layout.item_pintuan_tjtg);
        pintuanTjtgAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                PintuanShopListResponBean pslBean = (PintuanShopListResponBean) adapter.getItem(position);
                new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
                        pslBean.getId())
                        .startActivity(true);
            }
        });
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(mContext, 2);
        mGridLayoutManager.setSmoothScrollbarEnabled(true);
        recyclerView.setLayoutManager(mGridLayoutManager);
        recyclerView.setAdapter(pintuanTjtgAdapter);
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        pintuanTjtgAdapter.setNewData(pintuanShopListResponBeanList);
    }


    private void initHeadList(List<String> imageList) {
        if (pintuanheadListAdapter != null) {
            pintuanheadListAdapter.setNewData(imageList);
            return;
        }
        pintuanheadListAdapter = new PintuanheadListAdapter(R.layout.item_pintuan_head_list);
        GridLayoutManager mGridLayoutManager = new GridLayoutManager(mContext, 5);
        mGridLayoutManager.setSmoothScrollbarEnabled(true);
        pintuanUsersRecycleview.setLayoutManager(mGridLayoutManager);
        pintuanUsersRecycleview.setAdapter(pintuanheadListAdapter);
        pintuanheadListAdapter.setNewData(imageList);
    }

    @Override
    protected int getTitleIntText() {
        return R.string.pintuan_details_title;
    }

    @OnClick({R.id.layout_fuwu, R.id.layout_look_oreder_info, R.id.tv_share_join, R.id.layout_rule, R.id.tv_pintuan_no})
    public void doClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            return;
        }
        switch (view.getId()) {
            case R.id.layout_fuwu:
                //服务
//                if (pintuanFuwuPopup == null) {
//                    pintuanFuwuPopup = new PintuanFuwuPopup(mContext);
//                }
//                pintuanFuwuPopup.setPopupGravity(Gravity.BOTTOM);
//                pintuanFuwuPopup.showPopupWindow();
                //跳转到商品详情
                if (mPintuanHeadListResponBean == null) {
                    StyleableToast.makeText(mContext, "商品信息出错", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                new StartActivityUtil(mContext, PintuanShopDetailsActivity.class).putExtra(Constants.PINTUAN_SHOP_ID,
                        mPintuanHeadListResponBean.getGoods_id())
                        .startActivity(true);
                break;
            case R.id.layout_look_oreder_info:
                //查看订单详情
                if (mPintuanHeadListResponBean == null) {
                    StyleableToast.makeText(mContext, "未获取到信息", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                new StartActivityUtil(mContext, PintuanOrderDetailsActivity.class).putExtra(Constants.PINTUANORDER_NO, mPintuanHeadListResponBean.getOrder_id() + "")
                        .putExtra(Constants.PINTUANORDER_FROM, Constants.PINTUANORDER_FROM_HEAD_LIST)
                        .startActivity(true);
                break;
            case R.id.tv_share_join:
                //分享邀请好友
                //邀请好友
                if (mPintuanHeadListResponBean == null) {
                    StyleableToast.makeText(mContext, "未获取到信息", Toast.LENGTH_SHORT, R.style.mytoast).show();
                    return;
                }
                LoadingDialogUtils.show(mContext);
                mPresenter.getPtiptGoodsShare(mPintuanHeadListResponBean.getGoods_id()+"", mPintuanHeadListResponBean.getGroup_id());
                break;
            case R.id.layout_rule:
                //拼团规则
                LoadingDialogUtils.show(mContext);
                mPresenter.getPtiguize("1");
                break;
            case R.id.tv_pintuan_no:
                //复制拼团号
                if (mPintuanHeadListResponBean == null || TextUtils.isEmpty(mPintuanHeadListResponBean.getGroup_no())) {
                    return;
                }
                ClipboardUtils.copyText(mPintuanHeadListResponBean.getGroup_no(), "复制成功");
                break;
            default:
                break;
        }
    }


    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .titleBar(mToolbar, true)
                .transparentBar()
                .statusBarDarkFont(true)
                .init();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    public void showContent(PintuanHeadListResponBean bean) {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
        mPintuanHeadListResponBean = bean;
        List<String> imageList = bean.getUser_image_array();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        //获取拼团信息
        if (bean != null) {
            tvShopTitle.setText(TextUtils.isEmpty(bean.getGoods_name()) ? "" : bean.getGoods_name());
            if (bean.getGroup_status() == 1) {
                tvPintuanStatus.setText("还差" + bean.getResidue_user() + "人可成团，有" + bean.getGroup_sum() + "人在团它哦~");
                //启动倒计时
                long currenTime = System.currentTimeMillis() / 1000;
                long endTime = bean.getEnd_time();
                if (endTime > currenTime) {
                    long seconds = endTime - currenTime;
                    countDownTimer = new CountDownTimer(seconds * 1000, 1000) {
                        public void onTick(long l) {
                            tvPintuanNo.setText("距离拼团结束" + StringUtil.getTimeStr(l) + " 拼团号：" + bean.getGroup_no());
                        }

                        public void onFinish() {
                            //倒计时结束
                            LoadingDialogUtils.show(mContext);
                            mPresenter.getPtigroupUserImage(groupId + "");
                            //倒计时结束 刷新商品信息
                            RxBus.getDefault().post(new SendEvent("", Constants.TYPE_GET_SHOP_INFO));
                        }
                    }.start();
                }

            } else if (bean.getGroup_status() == 2) {
                tvPintuanStatus.setText("恭喜您，拼团成功");
                tvPintuanNo.setText("拼团号：" + bean.getGroup_no());
                tvShareJoin.setVisibility(View.GONE);
            } else if (bean.getGroup_status() == 3) {
                tvPintuanStatus.setText("很遗憾，拼团失败~");
                tvPintuanNo.setText("拼团号：" + bean.getGroup_no());
                tvShareJoin.setVisibility(View.GONE);
            }
            if (imageList == null) {
                imageList = new ArrayList<>();
            }
            for (int i = 0; i < bean.getResidue_user(); i++) {
                imageList.add("NO_DATA");
            }
        }
        initHeadList(imageList);
        //获取推荐商品
        mPresenter.getHotShopList(1);
    }

    @Override
    public void showContentError() {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
    }

    @Override
    public void showMoreContent(String list) {

    }

    @Override
    public void showPtiptGoodsShare(ShareResponBean shareResponBean) {

        LoadingDialogUtils.dismissDialog_ios();
        if (shareResponBean == null || TextUtils.isEmpty(shareResponBean.getShare_image())) {
            StyleableToast.makeText(mContext, "获取分享信息失败", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        if (mPintuanHeadListResponBean == null) {
            StyleableToast.makeText(mContext, "未获取到信息", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }

        String shareText = shareResponBean.getShare_text();

        if (shareShopPopup == null) {
            shareShopPopup = new ShareShopPopup(mContext, mContext, shareText, new ShareShopPopup.ItemClickCallback() {
                @Override
                public void saveImage(String url) {
                    if (!TextUtils.isEmpty(url)) {
                        PermissionUtil.requestPermissionForActivity(mContext, new PermissionUtil.IPermissionListener() {
                            @Override
                            public void permissionGranted() {
                                saveNetImageToLoacl(url);
                            }

                            @Override
                            public void permissionDenied() {
                                ToastUtil.show("权限被拒绝,请设置应用权限");
                            }
                        }, "权限被拒绝,请设置应用权限", PermissionUtil.scan_permissions);
                    }
                }
            });
        }
        float fromX = 0;
        float fromY = 1f;
        float toX = 0;
        float toY = 0;
        Animation showAnimation = createTranslateAnimation(fromX, toX, fromY, toY);
        Animation dismissAnimation = createTranslateAnimation(toX, fromX, toY, fromY);
        shareShopPopup.setShowAnimation(showAnimation);
        shareShopPopup.setDismissAnimation(dismissAnimation);
        shareShopPopup.setPopupGravity(Gravity.BOTTOM);
        shareShopPopup.setImgUrl(shareResponBean.getShare_image());
        shareShopPopup.showPopupWindow();
    }

    @Override
    public void showHotShopList(List<PintuanShopListResponBean> list) {
        //获取推荐团购数据
        LoadingDialogUtils.dismissDialog_ios();
        if (list == null) {
            list = new ArrayList<>();
        }
        if (list.size() > 4) {
            list = list.subList(0, 4);
        }
        initHotList(list);
    }

    @Override
    public void showPtiguize(RuleBean bean) {
        //获取规则成功
        LoadingDialogUtils.dismissDialog_ios();
        if (bean == null) {
            StyleableToast.makeText(mContext, "暂无数据", Toast.LENGTH_SHORT, R.style.mytoast).show();
            return;
        }
        new StartActivityUtil(mContext, PintuanRuleActivity.class)
                .putExtra(Constants.RULE_TITLE, bean.getIntroduce())
                .putExtra(Constants.RULE_CONTENT, bean.getContent())
                .startActivity(true);
    }

    private LoadImageDataThread mLoadDataThread;

    public void saveNetImageToLoacl(String downloadPath) {
        boolean isHttp = PictureMimeType.isHttp(downloadPath);
        LoadingDialogUtils.show(mContext, "保存中");
        if (isHttp) {
            mLoadDataThread = new LoadImageDataThread(downloadPath, mHandler, mContext);
            mLoadDataThread.start();
        }
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case Constants.SAVE_IMAGE_SUCCESSFUL:
                    try {
                        String path = (String) msg.obj;
                        if (!TextUtils.isEmpty(path)) {
                            if (!SdkVersionUtils.checkedAndroid_Q()) {
                                File file = new File(path);
                                MediaStore.Images.Media.insertImage(mContext.getContentResolver(), file.getAbsolutePath(), file.getName(), null);
                                new PictureMediaScannerConnection(mContext, file.getAbsolutePath(), () -> {
                                });
                            }
                            StyleableToast.makeText(mContext, "图片保存成功", R.style.mytoast).show();
                        }
                        LoadingDialogUtils.dismissDialog_ios();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case Constants.SAVE_IMAGE_ERROR:
                    ToastUtils.s(mContext, getString(R.string.picture_save_error));
                    LoadingDialogUtils.dismissDialog_ios();
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
            countDownTimer = null;
        }
        if (mLoadDataThread != null) {
            mHandler.removeCallbacks(mLoadDataThread);
            mLoadDataThread = null;
        }
    }
}
